<?php
/**
 * Created by PhpStorm.
 * User: mawenhuan
 * Date: 2017/12/23
 * Time: 下午2:22
 */

namespace App\Utils;


use OSS\OssClient;
use OSS\Core\OssException;

class OssUtil
{
	const OSS_ID = 'LTAI5tH2qsCJHkmMj4ySBB2Y';
	const OSS_KEY = 'GACvLU6Kz9854zkr3YiHuq2bXDA4CQ';
	const ENDPOINT = 'oss-cn-shenzhen.aliyuncs.com';
    const BUCKET = 'qfchou';

	/**
	 * @var
	 * @type OssClient
	 */
	private static $oss = [];

	/**
	 * @desc getOss
	 * @return OssClient
	 */
	public static function getOss()
	{
		if(empty(static::$oss['oss']) || !static::$oss['oss'] instanceof OssClient) {
            static::$oss['oss'] = new OssClient(self::OSS_ID, self::OSS_KEY, self::ENDPOINT);
        }
		return static::$oss['oss'];

       // return static::$oss['oss'] = new OssClient(self::OSS_ID, self::OSS_KEY, self::ENDPOINT);
	}

	public static function fetchGetSignUrl($object, $ssl = true, $process = null)
	{
		if (empty($object)){
			return "";
		}
		try{
			if($object[0] == '/'){
				$object = substr($object, 1, strlen($object) -1);
			}
			if (strpos($object, 'http') === 0){
				return $object;
			}

			//return ConfigUtil::url() . '/'. $object;

			// 按图片尺寸类型 缓存
            // 按图片尺寸类型 缓存
//            if(empty($process)) {
//                $key = RedisKeys::OSS_IMAGE_PRE . $object;
//            } else {
//                if(strpos($process, 'h_')) {
//                    $key = RedisKeys::OSS_IMAGE_PRE . $object . 'width:height';
//                } else {
//                    $key = RedisKeys::OSS_IMAGE_PRE . $object . 'width';
//                }
//            }

//			$signUrl = RedisUtil::get($key);
//            $urlParam = self::convertUrlQuery($signUrl) ?? 0;
//			if ($urlParam['Expires'] > (time() + 5)) {
//			    return $signUrl;
//            }
//			return $ssl ? 'https://static.saye-sports.com/' . $object : 'http://static.saye-sports.com/' . $object;
			$oss = static::getOss();
			if ($ssl)
				$oss->setUseSSL(true);
			$option = [];
			$option[OssClient::OSS_CACHE_CONTROL] = 3500;
            $option[OssClient::OSS_EXPIRES] = time() + 3500;
			if ($process) {
			    $option[OssClient::OSS_PROCESS] = $process;
            }
			$url = $oss->signUrl(self::BUCKET, $object, 1800, OssClient::OSS_HTTP_GET, $option);
//			$url = str_replace('saye.oss-cn-beijing.aliyuncs.com', 'static.saye-sports.com', $url);
            //RedisUtil::set($key, $url, 3400);
			return $url;
		}catch (\Exception $e){
			return $object;
		}
	}

    public static function convertUrlQuery($url)
    {
        if(empty($url)) {
            return 0;
        }
        $arr = parse_url($url);
        $queryParts = explode('&', $arr['query']);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }

	public static function fetchPutSignUrl($object)
	{
		$oss = static::getOss();
		return $oss->signUrl(self::BUCKET, $object, 1800, OssClient::OSS_HTTP_PUT);
	}

	public static function gmt_iso8601($time) {
		$dtStr = date("c", $time);
		$mydatetime = new \DateTime($dtStr);
		$expiration = $mydatetime->format(\DateTime::ISO8601);
		$pos = strpos($expiration, '+');
		$expiration = substr($expiration, 0, $pos);
		return $expiration."Z";
	}

	public static function fetchSts($type=2)
	{
		$type = $type == 1 ? 'videos' : 'images';

		$now = time();
		$expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
		$end = $now + $expire;
		$expiration = static::gmt_iso8601($end);

		// 根据type 设置 video image
		$dir = $type . '/' . date('Y') . '/' . date('m') . '/'. date('d'). '/';

		//最大文件大小.用户可以自己设置
		$condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
		$conditions[] = $condition;

		//表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
		$start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
		$conditions[] = $start;

		$arr = array('expiration'=>$expiration,'conditions'=>$conditions);
		$policy = json_encode($arr);
		$base64_policy = base64_encode($policy);
		$string_to_sign = $base64_policy;
		$signature = base64_encode(hash_hmac('sha1', $string_to_sign, self::OSS_KEY, true));
		$response = array();
		$response['accessid'] = self::OSS_ID;
		$response['host'] = 'https://' . self::BUCKET . '.' . self::ENDPOINT;
		$response['policy'] = $base64_policy;
		$response['signature'] = $signature;
		$response['expire'] = $end;
		//这个参数是设置用户上传指定的前缀
		$response['dir'] = $dir;
		return $response;
	}


	public static function uploadObject($object, $content, $option=[]): string
    {
        try {
            $ossClient = self::getOss();
            $ossClient->uploadFile(self::BUCKET, $object, $content);
            return $object;
        } catch (OssException $e) {
            //Log::error($e->getMessage());
            return $object;
        }
    }

}
